package com.jintu.portal.service.impl;

import com.jintu.portal.exception.ServiceException;
import com.jintu.portal.pojo.bean.*;
import com.jintu.portal.pojo.dto.ModifyPwdDto;
import com.jintu.portal.pojo.dto.RegisterDto;
import com.jintu.portal.pojo.dto.TobUserDto;
import com.jintu.portal.pojo.dto.TobUserReqDto;
import com.jintu.portal.pojo.entity.TCompany;
import com.jintu.portal.pojo.entity.TUser;
import com.jintu.portal.pojo.entity.TUserDepartmentPost;
import com.jintu.portal.repository.mysql.dao.CompanyDao;
import com.jintu.portal.repository.mysql.dao.UserDao;
import com.jintu.portal.repository.mysql.dao.UserDepartmentPostDao;
import com.jintu.portal.service.TobUserService;
import com.jintu.portal.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

/**
 * Created by junhu on 2017/9/28.
 */
@Slf4j
@Service
public class TobUserServiceImpl implements TobUserService {

    //private static Logger logger = (Logger) LoggerFactory.getLogger(TobUserServiceImpl.class);
    @Resource
    private UserDao userDao;
    @Resource
    private UserDepartmentPostDao userDepartmentPostDao;
//    @Autowired
//    private PostDao postDao;
//    @Autowired
//    private DepartmentDao departmentDao;
    @Resource
    private CompanyDao companyDao;


    @Value("${customer_service_phone}")
    private String customerServicePhone;

    /**
     * B端用户注册
     * @param registerDto
     * @throws Exception
     */
    @Transactional
    public void register(RegisterDto registerDto) throws Exception {
        QLBuilder ql = new QLBuilder();
        ql.and(Filter.eq("username", registerDto.getUserName()));
        ql.and(Filter.eq("system", SystemType.B_APP_SYSTEM.getValue()));
        ql.and(Filter.eq("logicDelete", LogicDelete.NOT_DELETE.getValue()));
        TUser user = userDao.findOneByJpql(ql);
        if(user != null) {
            throw new ServiceException("该手机号已经在商家运营平台注册，不能重复注册");
        }
        user = BeanUtils.copyProperties(registerDto, TUser.class);
        String password = StringUtil.toMD5(registerDto.getUserName()+registerDto.getPwd());
        user.setPassword(password);
        user.setRealname(registerDto.getRealName());
        user.setUsername(registerDto.getUserName());
        user.setSystem(SystemType.B_APP_SYSTEM.getValue());
        user.setLogicDelete(LogicDelete.NOT_DELETE.getValue());
        user.setStatus(UserStatus.INCUMBENCY.getValue());
        user.setCreateTime(new Date());
        user.setCompanyId(10L);
        user.setAddType(AddType.ADD.getValue());
        userDao.insert(user);
        //添加用户部门关联表
        TUserDepartmentPost userDepartmentPost = new TUserDepartmentPost();
        userDepartmentPost.setUserId(user.getId());
        userDepartmentPost.setDepartmentId(30L);
        userDepartmentPost.setPostId(16L);
        userDepartmentPost.setIsUsed(IsUsed.USED.getValue());
        userDepartmentPostDao.insert(userDepartmentPost);
        //RedisUtil 中清除对应的验证码缓存

    }

    /**
     * 员工输入密码正常登录
     * @param username
     * @param pwd
     * @param systemType
     * @return
     * @throws Exception
     */
    public List<TobUserDto> login(String username, String pwd, SystemType systemType) throws Exception {

        QLBuilder ql = new QLBuilder();
        ql.and(Filter.eq("username", username));
        ql.and(Filter.eq("logicDelete", LogicDelete.NOT_DELETE.getValue()));
        ql.and(Filter.eq("system", systemType.getValue()));
        TUser user = userDao.findOneByJpql(ql);
        if(user == null){
            throw new ServiceException("该手机号尚未进行注册!");
        }
        TCompany company = companyDao.get(user.getCompanyId());
        if(company.getIsUsed() == IsUsed.NOT_USED.getValue()) {
            throw new ServiceException("该公司已被停止服务");
        }
        if(!user.getPassword().equals(StringUtil.toMD5(username+pwd))) {
            throw new ServiceException("密码错误!");
        }
        if(user.getStatus() == UserStatus.PENDING.getValue()){
            throw new ServiceException("该手机号尚未通过审核，请耐心等待!");
        }

        ql = new QLBuilder();
        ql.setMainClause("SELECT new com.jintu.portal.pojo.dto.TobUserDto(tudp,tdep,tp,tu,tc) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu,TCompany tc WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id and tdep.companyId = tc.id and tu.companyId = tc.id");
        ql.and(Filter.eq("tu.id", user.getId()));
        ql.and(Filter.eq("tudp.isUsed", IsUsed.USED.getValue()));
        ql.and(Filter.eq("tu.system", systemType.getValue()));
        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
        List<TobUserDto> tobUserDtoList = userDepartmentPostDao.findManyByJpql(ql);
        if(CollectionUtils.isEmpty(tobUserDtoList)){
            //校验用户是否停用
            throw new ServiceException("当前账号已停用，暂时无法登录!");
        }
        Integer manyRole = ManyRoleType.MANYROLE_NO.getValue();//默认为单角色
        if(tobUserDtoList.size()>1){
            manyRole = ManyRoleType.MANYROLE_YES.getValue();
        }
        UserUtil.removeTobUser(user.getId());
        StringBuffer departmentPostKey = null;
        for (TobUserDto tobUserDto : tobUserDtoList) {
            tobUserDto.setManyRole(manyRole);
            String key = null;
            for (int i = 0; i < 5; i++) {
                key = UserUtil.USER_TOKEN_KEY_HEADER + ":" + StringUtil.getUUID();
                if(!RedisUtil.INSTANCE.exists(key)) {
                    break;
                }
            }
            tobUserDto.setToken(key);
            RedisUtil.INSTANCE.set(key, tobUserDto, UserUtil.TOB_USER_EXPIRE);
            departmentPostKey = new StringBuffer();
            departmentPostKey.append(key).append(":company:").append(tobUserDto.getCompanyId()).append(":department:").append(tobUserDto.getDepartmentId()).append(":post:").append(tobUserDto.getPostId()).append(":user:").append(tobUserDto.getUserId());
            RedisUtil.INSTANCE.set(departmentPostKey.toString(), key, UserUtil.TOB_USER_EXPIRE);
        }
        return tobUserDtoList;
    }

    /**
     * 动态校验码登录
     * @param username
     * @param vaildCode
     * @param systemType
     * @return
     * @throws Exception
     */
    public List<TobUserDto> dynamicLogin(String username, String vaildCode, SystemType systemType) throws Exception {

        QLBuilder ql = new QLBuilder();
        ql.and(Filter.eq("username", username));
        ql.and(Filter.eq("logicDelete", LogicDelete.NOT_DELETE.getValue()));
        ql.and(Filter.eq("system", systemType.getValue()));
        TUser user = userDao.findOneByJpql(ql);
        if(user == null){
            throw new ServiceException("该手机号尚未进行注册!");
        }
        TCompany company = companyDao.get(user.getCompanyId());
        if(company.getIsUsed() == IsUsed.NOT_USED.getValue()) {
            throw new ServiceException("该公司已被停止服务");
        }
        if(user.getStatus() == UserStatus.PENDING.getValue()){
            throw new ServiceException("该手机号尚未通过审核，请耐心等待!");
        }
        //判断验证码是否错误
        String codeError = RedisUtil.INSTANCE.get("dynamicCodeError"+username);
        if(!vaildCode.equals(codeError)) {
            throw new ServiceException("动态密码错误!");
        }
        //判断验证码是否失效
        Date activeTime = RedisUtil.INSTANCE.get("dynamicCodeAbate"+username,Date.class);
        if(activeTime == null){
            throw new ServiceException("获取动态密码异常!");
        }
        if(DateUtil.getBetweenDateSecond(activeTime,new Date()) > 300) {
            throw new ServiceException("动态密码已失效，请重新获取!");
        }
        //登录成功后清除验证码信息
        if(StringUtil.isNotEmpty(codeError)){
            RedisUtil.INSTANCE.delete("dynamicCodeError"+username);
        }
        ql = new QLBuilder();
        ql.setMainClause("SELECT new com.jintu.portal.pojo.dto.TobUserDto(tudp,tdep,tp,tu,tc) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu,TCompany tc WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id and tdep.companyId = tc.id and tu.companyId = tc.id");
        ql.and(Filter.eq("tu.id", user.getId()));
        ql.and(Filter.eq("tudp.isUsed", IsUsed.USED.getValue()));
        ql.and(Filter.eq("tu.system", systemType.getValue()));
        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
        List<TobUserDto> tobUserDtoList = userDepartmentPostDao.findManyByJpql(ql);
        if(CollectionUtils.isEmpty(tobUserDtoList)){
            //校验用户是否停用
            throw new ServiceException("当前账号已停用，暂时无法登录!");
        }
        Integer manyRole = ManyRoleType.MANYROLE_NO.getValue();//默认为单角色
        if(tobUserDtoList.size()>1){
            manyRole = ManyRoleType.MANYROLE_YES.getValue();
        }
        UserUtil.removeTobUser(user.getId());
        StringBuffer departmentPostKey = null;
        for (TobUserDto tobUserDto : tobUserDtoList) {
            tobUserDto.setManyRole(manyRole);
            String key = null;
            for (int i = 0; i < 5; i++) {
                key = UserUtil.USER_TOKEN_KEY_HEADER + ":" + StringUtil.getUUID();
                if(!RedisUtil.INSTANCE.exists(key)) {
                    break;
                }
            }
            tobUserDto.setToken(key);
            RedisUtil.INSTANCE.set(key, tobUserDto, UserUtil.TOB_USER_EXPIRE);
            departmentPostKey = new StringBuffer();
            departmentPostKey.append(key).append(":company:").append(tobUserDto.getCompanyId()).append(":department:").append(tobUserDto.getDepartmentId()).append(":post:").append(tobUserDto.getPostId()).append(":user:").append(tobUserDto.getUserId());
            RedisUtil.INSTANCE.set(departmentPostKey.toString(), key, UserUtil.TOB_USER_EXPIRE);
        }
        return tobUserDtoList;
    }

    /**
     * B端根据不同操作类型，发送验证码
     * 1用户注册验证码，2动态登录验证码，3忘记密码注册码
     * @param phone
     * @param codeType
     * @param systemType
     */
    public void sendCodeByType(String phone,Integer codeType, SystemType systemType) throws Exception {
        String code = StringUtil.getRadomString(6, 0);
        if(codeType == CodeType.B_REGISTER_CODE.getValue()){
            //验证码和验证码失效时间设置5分钟
            RedisUtil.INSTANCE.set("registerCodeError"+phone, code,600);
            RedisUtil.INSTANCE.set("registerCodeAbate"+phone, new Date(),600);
            //发送验证码
            SmsUtil.send(phone, MsgType.REGISTER_CODE,code);
        }else if(codeType == CodeType.B_DYNAMIC_CODE.getValue()){
            RedisUtil.INSTANCE.set("dynamicCodeError"+phone, code,600);
            RedisUtil.INSTANCE.set("dynamicCodeAbate"+phone, new Date(),600);
            SmsUtil.send(phone, MsgType.DYNAMIC_PWD,code);
        }else if(codeType == CodeType.B_FORGET_CODE.getValue()){
            RedisUtil.INSTANCE.set("forgetCodeError"+phone, code,600);
            RedisUtil.INSTANCE.set("forgetCodeAbate"+phone, new Date(),600);
            SmsUtil.send(phone, MsgType.FORGET_CODE,code);
        }
    }

    /**
     * B端忘记密码-修改密码,需要登录
     * @param modifyPwdDto
     * @param systemType
     */
    @Transactional
    public void forgetPwdModify(ModifyPwdDto modifyPwdDto, SystemType systemType) {
        //验证码错误或失效
        String codeError = RedisUtil.INSTANCE.get("forgetCodeError"+modifyPwdDto.getUsername());
        if(!modifyPwdDto.getVerifyCode().equals(codeError)) {
            throw new ServiceException("验证码错误!");
        }
        Date activeTime = RedisUtil.INSTANCE.get("forgetCodeAbate"+modifyPwdDto.getUsername(),Date.class);
        if(DateUtil.getBetweenDateSecond(activeTime,new Date()) > 300) {
            throw new ServiceException("验证码已失效，请重新获取!");
        }
        //忘记密码验证成功后清除验证码信息
        if(StringUtil.isNotEmpty(codeError)){
            RedisUtil.INSTANCE.delete("forgetCodeError"+modifyPwdDto.getUsername());
        }
        QLBuilder ql = new QLBuilder();
        ql.and(Filter.eq("username", modifyPwdDto.getUsername()));
        ql.and(Filter.eq("logicDelete", LogicDelete.NOT_DELETE.getValue()));
        ql.and(Filter.eq("system", systemType.getValue()));
        TUser user = userDao.findOneByJpql(ql);
        if(user == null) {
            throw new ServiceException("该手机号尚未注册!");
        }
        String password = StringUtil.toMD5(modifyPwdDto.getUsername()+modifyPwdDto.getPwd());
        user.setPassword(password);
        user.setUpdateTime(new Date());
        user.setUpdater(user.getId());
        userDao.update(user);
    }
//
//    /**
//     * 切换角色
//     * @param userId
//     * @param systemType
//     * @return
//     * @throws Exception
//     */
//    public List<TobUserDto> userRoleChange(Long userId, SystemType systemType) throws Exception {
//        //查询该用户对应的所有角色信息
//        QLBuilder ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.common.dto.org.TobUserDto(tudp,tdep,tp,tu,tc) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu,TCompany tc WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id and tdep.companyId = tc.id and tu.companyId = tc.id");
//        ql.and(Filter.eq("tu.id", userId));
//        ql.and(Filter.eq("tudp.isUsed", IsUsed.USED.getValue()));
//        ql.and(Filter.eq("tu.system", systemType.getValue()));
//        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        List<TobUserDto> tobUserDtoList = userDepartmentPostDao.findManyByJpql(ql);
//        Integer manyRole = ManyRoleType.MANYROLE_NO.getValue();//默认为单角色
//        if(tobUserDtoList.size()>1){
//            manyRole = ManyRoleType.MANYROLE_YES.getValue();
//        }
//        List<TobUserDto> userDtoList = new ArrayList<TobUserDto>();
//        //UserUtil.removeTobUser(userId);
//        StringBuffer departmentPostKey = null;
//        for (TobUserDto tobUserDto : tobUserDtoList) {
//            Set<String> keySet =RedisUtil.INSTANCE.keys(UserUtil.USER_TOKEN_KEY_HEADER +":*:department:"+tobUserDto.getDepartmentId() +":post:"+tobUserDto.getPostId() + ":user:"+tobUserDto.getUserId());
//            boolean flag = true;
//            if(keySet != null && keySet.size()>0){
//                TobUserDto redisTobUserDto = null;
//                String userKey = null;
//                for (String key : keySet) {
//                    userKey =  RedisUtil.INSTANCE.get(key);
//                    redisTobUserDto = RedisUtil.INSTANCE.get(userKey, TobUserDto.class);
//                    tobUserDto.setManyRole(manyRole);
//                    tobUserDto.setToken(redisTobUserDto.getToken());
//                    userDtoList.add(tobUserDto);
//                    flag = false;
//                    break;
//                }
//            }
//            if(flag){
//                tobUserDto.setManyRole(manyRole);
//                String key = null;
//                for (int i = 0; i < 5; i++) {
//                    key = UserUtil.USER_TOKEN_KEY_HEADER + ":" + StringUtil.getUUID();
//                    if(!RedisUtil.INSTANCE.exists(key)) {
//                        break;
//                    }
//                }
//                tobUserDto.setToken(key);
//                RedisUtil.INSTANCE.set(key, tobUserDto, UserUtil.TOB_USER_EXPIRE);
//                departmentPostKey = new StringBuffer();
//                departmentPostKey.append(key).append(":company:").append(tobUserDto.getCompanyId()).append(":department:").append(tobUserDto.getDepartmentId()).append(":post:").append(tobUserDto.getPostId()).append(":user:").append(tobUserDto.getUserId());
//                RedisUtil.INSTANCE.set(departmentPostKey.toString(), key, UserUtil.TOB_USER_EXPIRE);
//                userDtoList.add(tobUserDto);
//            }
//        }
//        return userDtoList;
//    }
//
//    /**
//     * B端 部门下的员工(有效的)
//     * @param departmentId
//     * @return
//     * @throws Exception
//     */
//    public List<TobUserDto> departmentUserList(Long departmentId, SystemType systemType) throws Exception {
//        QLBuilder ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.common.dto.org.TobUserDto(tudp,tdep,tp,tu,tc) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu,TCompany tc WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id and tdep.companyId = tc.id and tu.companyId = tc.id");
//        ql.and(Filter.eq("tdep.id", departmentId));
//        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        ql.and(Filter.eq("tu.status", UserStatus.INCUMBENCY.getValue()));
//        ql.and(Filter.eq("tu.system", systemType.getValue()));
//        return userDepartmentPostDao.findManyByJpql(ql);
//    }
//
//    /**
//     * B端 部门下的员工(包括已删除即离职的)
//     * @param departmentId
//     * @return
//     * @throws Exception
//     */
//    public List<TobUserDto> departmentAllUserList(Long departmentId, SystemType systemType) throws Exception {
//        QLBuilder ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.common.dto.org.TobUserDto(tudp,tdep,tp,tu,tc) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu,TCompany tc WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id and tdep.companyId = tc.id and tu.companyId = tc.id");
//        ql.and(Filter.eq("tdep.id", departmentId));
//        //ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        ql.and(Filter.eq("tu.system", systemType.getValue()));
//        List<TobUserDto> userDtoList = userDepartmentPostDao.findManyByJpql(ql);
//        return userDtoList;
//    }
//
    /**
     * B端用户详情信息
     * @param departmentId
     * @param userId
     * @param systemType
     * @return
     * @throws Exception
     */
    public TobUserDto tobUserDetail(Long departmentId, Long userId, Long postId, SystemType systemType) throws Exception {
        QLBuilder ql = new QLBuilder();
        ql.setMainClause("SELECT new com.jintu.portal.pojo.dto.TobUserDto(tudp,tdep,tp,tu,tc) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu,TCompany tc WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id and tdep.companyId = tc.id and tu.companyId = tc.id");
        ql.and(Filter.eq("tu.id", userId));
        ql.and(Filter.eq("tdep.id", departmentId));
        ql.and(Filter.eq("tudp.postId",postId));
        //ql.and(Filter.eq("tudp.isUsed",IsUsed.USED.getValue()));
        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
        TobUserDto tobUserDto = userDepartmentPostDao.findOneByJpql(ql);
        if(null != tobUserDto){
            //是否多角色标志
            ql = new QLBuilder();
            ql.and(Filter.eq("userId",userId));
            ql.and(Filter.eq("isUsed",IsUsed.USED.getValue()));
            List<TUserDepartmentPost> userDepartmentPostList = userDepartmentPostDao.findManyByJpql(ql);
            Integer manyRole = ManyRoleType.MANYROLE_NO.getValue();
            if(!CollectionUtils.isEmpty(userDepartmentPostList) && userDepartmentPostList.size()>1){
                manyRole = ManyRoleType.MANYROLE_YES.getValue();
            }
            tobUserDto.setManyRole(manyRole);
        }

        return tobUserDto;
    }
//
//    /**
//     * B端管理员对员工相关操作
//     * 用户操作类1停用，2启用，3通过，4拒绝，5离职
//     * @param userReqDto
//     * @throws Exception
//     */
//    @Transactional
//    public void tobUserOper(TobUserReqDto userReqDto) throws Exception {
////        userReqDto.setUserDepartmentId(4679L);
////        TUserDepartmentPost userDepartmentPost = userDepartmentPostDao.get(userReqDto.getUserDepartmentId());;
////        if(userReqDto.getOperType() == UserOperType.STOPOPER.getValue()){
////            //userDepartmentPost = userDepartmentPostDao.get(userReqDto.getUserDepartmentId());
////            userDepartmentPost.setIsUsed(IsUsed.NOT_USED.getValue());
////            userDepartmentPostDao.update(userDepartmentPost);
////            TDepartment department = departmentDao.get(userDepartmentPost.getDepartmentId());
////            TPost post = postDao.get(userDepartmentPost.getPostId());
////            //发送短信信息
//////            SmsUtil.send(userReqDto.getPhoneNo(), MsgType.TOB_USER_STOP,department.getShortName(),post.getName());
////            //TODO 将B端用户强制退出
//////            UserUtil.expireUserPost(userDepartmentPost.getDepartmentId(),userDepartmentPost.getPostId(),userDepartmentPost.getUserId());
////        }else if(userReqDto.getOperType() == UserOperType.STARTOPER.getValue()){
////            QLBuilder ql = new QLBuilder();
////            ql.and(Filter.eq("userId",userReqDto.getUserId()));
////            ql.and(Filter.eq("isUsed",IsUsed.USED.getValue()));
////            ql.and(Filter.eq("departmentId",userDepartmentPost.getDepartmentId()));
////            List<TUserDepartmentPost> userDepartmentPostDtoList = userDepartmentPostDao.findManyByJpql(ql);
////            TUser user = userDao.get(userReqDto.getUserId());
////            TDepartment department = departmentDao.get(userDepartmentPost.getDepartmentId());
////            if(!CollectionUtils.isEmpty(userDepartmentPostDtoList)){
////                throw new ServiceException("当前员工（"+user.getRealname()+"）已经在（"+department.getShortName()+"）拥有其他岗位，无法恢复当前职位！");
////            }else{
////                TPost post = postDao.get(userDepartmentPost.getPostId());
////                userDepartmentPost.setIsUsed(IsUsed.USED.getValue());
////                userDepartmentPostDao.update(userDepartmentPost);
////                //发送短信信息
//////                SmsUtil.send(user.getUsername(), MsgType.USER_START,department.getShortName(),post.getName());
////            }
////        }else if(userReqDto.getOperType() == UserOperType.PASSOPER.getValue()){
////            TUser user = userDao.get(userDepartmentPost.getUserId());
////            user.setStatus(UserStatus.INCUMBENCY.getValue());
////            user.setUpdateTime(new Date());
//////            user.setUpdater(UserUtil.tobCurrentUser().getUserId());
//////            user.setAuditor(UserUtil.tobCurrentUser().getUserId());
////            user.setAuditTime(new Date());
////            userDao.update(user);
////            //更新对应部门可用
////            userDepartmentPost.setIsUsed(IsUsed.USED.getValue());
////            userDepartmentPostDao.update(userDepartmentPost);
////            //发送短信信息
//////            SmsUtil.send(userReqDto.getPhoneNo(), MsgType.USER_CHECK_SUCC,userReqDto.getPhoneNo());
////        }else if(userReqDto.getOperType() == UserOperType.REFUSEOPER.getValue()){
////            TUser user = userDao.get(userDepartmentPost.getUserId());
////            user.setLogicDelete(LogicDelete.DELETE.getValue());
////            user.setUpdateTime(new Date());
////            user.setUpdater(UserUtil.tobCurrentUser().getUserId());
////            user.setAuditor(UserUtil.tobCurrentUser().getUserId());
////            user.setAuditTime(new Date());
////            userDao.update(user);
////            // 发送短信信息
//////            SmsUtil.send(userReqDto.getPhoneNo(), MsgType.USER_REFUED);
////        }
//
//    }
//
    /**
     * 更新员工信息（1姓名，2手机号，3微信，4QQ，5生日）
     * @param tobUserReqDto
     * @throws Exception
     */
    @Transactional
    public TobUserDto updateEmployee(TobUserReqDto tobUserReqDto,String token) throws Exception {

        TUser user = userDao.get(tobUserReqDto.getUserId());
        if(user == null){
            throw new ServiceException("获取用户信息异常!");
        }
        QLBuilder ql = new QLBuilder();
        ql.setMainClause("SELECT new com.jintu.portal.pojo.dto.TobUserDto(tudp,tdep,tp,tu,tc) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu,TCompany tc WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id and tdep.companyId = tc.id and tu.companyId = tc.id");
        ql.and(Filter.eq("tu.id", tobUserReqDto.getUserId()));
        ql.and(Filter.eq("tdep.id", tobUserReqDto.getDepartmentId()));
        ql.and(Filter.eq("tudp.isUsed",IsUsed.USED.getValue()));
        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
        TobUserDto tobUserDto = userDepartmentPostDao.findOneByJpql(ql);
        tobUserDto.setToken(token);
        if(UserInfoType.EMPLOYEE_NAME.getValue() == tobUserReqDto.getUserInfoType()){
            updateEmployeeName(user,tobUserReqDto.getRealName());
            tobUserDto.setRealname(tobUserReqDto.getRealName());
        }else if(UserInfoType.EMPLOYEE_MOBILE.getValue() == tobUserReqDto.getUserInfoType()){
//            updateEmployeeMobile(user,tobUserReqDto);
//            tobUserDto.setPhone(tobUserReqDto.getPhoneNo());
        }else if(UserInfoType.EMPLOYEE_WECHAT.getValue() == tobUserReqDto.getUserInfoType()){
//            updateEmployeeWechat(user,tobUserReqDto.getWx());
//            tobUserDto.setWx(tobUserReqDto.getWx());
        }else if(UserInfoType.EMPLOYEE_QQ.getValue() == tobUserReqDto.getUserInfoType()){
//            updateEmployeeQq(user,tobUserReqDto.getQq());
//            tobUserDto.setQq(tobUserReqDto.getQq());
        }else if(UserInfoType.EMPLOYEE_BIRTHDAY.getValue() == tobUserReqDto.getUserInfoType()){
//            updateEmployeeBirthday(user,tobUserReqDto.getBirthday());
//            tobUserDto.setBirthday(tobUserReqDto.getBirthday());
        }
        return tobUserDto;
    }
//
//    /**
//     * 更新生日
//     * @param user
//     * @param birthdy
//     */
//    private void updateEmployeeBirthday(TUser user, String birthdy) {
//        user.setBirthday(birthdy);
//        user.setUpdateTime(new Date());
//        user.setUpdater(user.getId());
//        userDao.update(user);
//    }
//
//    /**
//     * 更新QQ
//     * @param user
//     * @param qq
//     */
//    private void updateEmployeeQq(TUser user, String qq) {
//        user.setQq(qq);
//        user.setUpdateTime(new Date());
//        user.setUpdater(user.getId());
//        userDao.update(user);
//    }
//
//    /**
//     *更新微信
//     * @param user
//     * @param wx
//     */
//    private void updateEmployeeWechat(TUser user, String wx) {
//        user.setWx(wx);
//        user.setUpdateTime(new Date());
//        user.setUpdater(user.getId());
//        userDao.update(user);
//    }
//
//    /**
//     * 换绑手机
//     * @param user
//     * @param tobUserReqDto
//     */
//    private void updateEmployeeMobile(TUser user, TobUserReqDto tobUserReqDto) throws Exception {
//        //验证码错误或失效
//        String codeError = RedisUtil.INSTANCE.get("changeCodeError"+tobUserReqDto.getPhoneNo());
//        if(!tobUserReqDto.getVerifyCode().equals(codeError)) {
//            throw new ServiceException("验证码错误!");
//        }
//        Date  activeTime  = RedisUtil.INSTANCE.get("changeCodeAbate"+tobUserReqDto.getPhoneNo(), Date.class);
//        if(DateUtil.getBetweenDateSecond(activeTime,new Date()) > 300) {
//            throw new ServiceException("验证码已失效，请重新获取!");
//        }
//        //原密码错误
//        if(!user.getPassword().equals(StringUtil.toMD5(user.getUsername()+tobUserReqDto.getSrcPwd()))) {
//            throw new ServiceException("密码错误!");
//        }
//        //验证成功后清除验证码信息
//        if(StringUtil.isNotEmpty(codeError)){
//            RedisUtil.INSTANCE.delete("changeCodeError"+tobUserReqDto.getPhoneNo());
//        }
//        user.setUsername(tobUserReqDto.getPhoneNo());
//        user.setPassword(StringUtil.toMD5(tobUserReqDto.getPhoneNo()+tobUserReqDto.getSrcPwd()));
//        user.setUpdateTime(new Date());
//        user.setUpdater(user.getId());
//        userDao.update(user);
//        //换绑成功发送短信
//        SmsUtil.send(tobUserReqDto.getPhoneNo(), MsgType.USER_CHANGE_PHONE_SUCCESS,tobUserReqDto.getPhoneNo(),customerServicePhone);
//    }
//
    /**
     * 修改姓名
     * @param user
     * @param realname
     */
    private void updateEmployeeName(TUser user, String realname) {
        user.setRealname(realname);
        user.setUpdateTime(new Date());
        user.setUpdater(user.getId());
        userDao.update(user);
    }

    /**
     * B端 上传修改头像
     * @param userId
     * @param uploadFile
     * @return
     * @throws Exception
     */
    @Transactional
    public String uploadFile(Long userId, MultipartFile uploadFile) throws Exception {
        log.info("入参:"+ userId);
        String filePath = null;
        // 把图片转化为文件
        String upload = FileUtil.getYmdUploadDir("image");
        String filePathTemp = FileUtil.upload(upload, uploadFile.getBytes(), FileUtil.getDestFileName(uploadFile.getName()));
        File f = new File(filePathTemp);

        //更新用户信息
        TUser user = userDao.get(userId);
        user.setHeadimgUrl("http://47.97.210.87" + filePathTemp);
        user.setUpdateTime(new Date());
        userDao.update(user);
        log.info("返回参数"+"http://47.97.210.87" + filePathTemp);
        return "http://47.97.210.87" + filePathTemp;
    }
//
//    /**
//     * bumen 部门类型下的岗位集合
//     * @param departmentTypeId
//     * @param bAppSystem
//     * @return
//     * @throws Exception
//     */
//    public List<PostDto> departmentPostList(Long departmentTypeId, SystemType bAppSystem) throws Exception {
//        QLBuilder ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.common.dto.org.PostDto(tp) from TPost tp");
//        ql.and(Filter.eq("tp.departmentTypeId", departmentTypeId));
//        ql.and(Filter.eq("tp.logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        List<PostDto> postDtoList = postDao.findManyByJpql(ql);
//        return postDtoList;
//    }
//
//    @Transactional
//    public void syncClientId(Long userId, String clientId) {
//        TUser user = userDao.get(userId);
//        user.setClientId(clientId);
//        userDao.update(user);
//    }
//
    /**
     * 校验用户是否都已经被停用
     * @param userId
     * @throws Exception
     */
    public void validUserStop(Long userId) throws Exception {
        QLBuilder ql = new QLBuilder();
        ql.setMainClause("SELECT new com.jintu.portal.pojo.dto.TobUserDto(tudp,tdep,tp,tu,tc) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu,TCompany tc WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id and tdep.companyId = tc.id and tu.companyId = tc.id");
        ql.and(Filter.eq("tu.id", userId));
        ql.and(Filter.eq("tudp.isUsed", IsUsed.USED.getValue()));
        ql.and(Filter.eq("tu.system", SystemType.B_APP_SYSTEM.getValue()));
        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
        List<TobUserDto> tobUserDtoList = userDepartmentPostDao.findManyByJpql(ql);
        if(CollectionUtils.isEmpty(tobUserDtoList)){
            //校验用户是否停用
            throw new ServiceException("当前账号已停用，暂时无法登录!");
        }
    }
//
//    /**
//     * 扫码注册校验
//     * @param registerDto
//     * @throws Exception
//     */
//    public void registerCheck(RegisterDto registerDto) throws Exception {
//        TCompany company = companyDao.get(registerDto.getCompanyId());
//        if(company.getIsUsed() == IsUsed.NOT_USED.getValue()) {
//            throw new ServiceException("该公司已被停止服务!");
//        }
//        TDepartment department = departmentDao.get(registerDto.getDepartmentId());
//        if(department.getLogicDelete() == LogicDelete.DELETE.getValue()) {
//            throw new ServiceException("该部门已经被删除!");
//        }
//    }
//
//    /**
//     * B端APP 获取店长(管理者)的相关部门及岗位
//     * @param managerPhoneNo 管理者的手机号码
//     * @param departmentId 部门ID
//     * @param postId 岗位ID
//     * @return
//     * @throws Exception
//     */
//    public List<DepartmentPostDto> getUserDepartmentAndPostList(String managerPhoneNo, Long departmentId, Long postId)throws Exception{
//        List<DepartmentPostDto> rsList = null;
//
//        StringBuffer sb = new StringBuffer("select td.id departmentId,td.short_name departmentName,tc.id companyId,tdtypepost.id postId,tdtypepost.`name` postName "+
//                                           "from t_user_department_post tudp,t_department td,t_post tp,t_user tu,t_company tc,t_post tdtypepost ");
//        sb.append("where tudp.department_id=td.id and tudp.post_id=tp.id and tudp.user_id=tu.id and td.company_id = tc.id and tu.company_id = tc.id "+
//                  "and tu.username= :username and tu.system= :system and tu.logic_delete= :logicDelete and tu.`status`= :status and tudp.is_used= :isUsed "+
//                  "and td.is_used= :isUsed and td.logic_delete= :logicDelete and tp.logic_delete= :logicDelete and tp.type= :type and tc.is_used= :isUsed "+
//                  "and td.department_type_id = tdtypepost.department_type_id and tdtypepost.logic_delete= :logicDelete ");
//        List<Object> params = new ArrayList<Object>();
//        params.add(managerPhoneNo);
//        params.add(SystemType.B_APP_SYSTEM.getValue());
//        params.add(LogicDelete.NOT_DELETE.getValue());
//        params.add(UserStatus.INCUMBENCY.getValue());
//        params.add(IsUsed.USED.getValue());
//        params.add(IsUsed.USED.getValue());
//        params.add(LogicDelete.NOT_DELETE.getValue());
//        params.add(LogicDelete.NOT_DELETE.getValue());
//        params.add(IsAdmin.ADMIN.getValue());
//        params.add(IsUsed.USED.getValue());
//        params.add(LogicDelete.NOT_DELETE.getValue());
//        if(departmentId != null){
//            sb.append("and td.id = :departmentId ");
//            params.add(departmentId);
//        }
//        if(postId != null){
//            sb.append("and tdtypepost.id = :postId ");
//            params.add(postId);
//        }
//        sb.append("order by tdtypepost.id");
//
//        List<DepartmentPostDto> list =  userDao.findManyBySql(sb.toString(), DepartmentPostDto.class, params.toArray());
//        if(list != null && list.size() > 0){
//            Map<String,Object> departmentIdMap = new HashMap<String,Object>();
//            List<Map<String,Object>> postList = null;
//            Map<String,Object> postMap = null;
//            DepartmentPostDto newDto = null;
//            for(DepartmentPostDto dto : list){
//                postMap = new HashMap<String,Object>();
//                postMap.put("postId",dto.getPostId());
//                postMap.put("postName",dto.getPostName());
//                if(departmentIdMap.containsKey(dto.getDepartmentId().toString())){
//                    newDto = (DepartmentPostDto)departmentIdMap.get(dto.getDepartmentId().toString());
//                    postList = newDto.getPostList();
//                    postList.add(postMap);
//                    departmentIdMap.put(dto.getDepartmentId().toString(),newDto);
//                }else{
//                    //不存在，新增
//                    postList = new ArrayList<Map<String, Object>>();
//                    postList.add(postMap);
//                    dto.setPostList(postList);
//                    departmentIdMap.put(dto.getDepartmentId().toString(),dto);
//                }
//            }
//            rsList = new ArrayList<DepartmentPostDto>();
//            Iterator iterDepartData = departmentIdMap.entrySet().iterator();
//            while (iterDepartData.hasNext()) {
//                Map.Entry entryDepartData = (Map.Entry) iterDepartData.next();
//                rsList.add((DepartmentPostDto)entryDepartData.getValue());
//            }
//        }
//
//        return rsList;
//    }
//
//    /**
//     * B端APP注册(直接页面)
//     * @param pageRegisterDto
//     * @throws Exception
//     */
//    @Transactional
//    public void pageRegister(PageRegisterDto pageRegisterDto) throws Exception{
//        //校验注册的手机号码是否有效
//        QLBuilder ql = new QLBuilder();
//        ql.and(Filter.eq("username", pageRegisterDto.getUserName()));
//        ql.and(Filter.eq("system", SystemType.B_APP_SYSTEM.getValue()));
//        ql.and(Filter.eq("logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        TUser user = userDao.findOneByJpql(ql);
//        if(user != null) {
//            throw new ServiceException("该手机号已经在商家运营平台注册，不能重复注册");
//        }
//        //校验店长所在部门及岗位是否有效
//        List<DepartmentPostDto> managerDepartmentPostList = getUserDepartmentAndPostList(pageRegisterDto.getManagerPhoneNo(),pageRegisterDto.getDepartmentId(),pageRegisterDto.getPostId());
//        if(managerDepartmentPostList == null || managerDepartmentPostList.size() < 1){
//            throw new ServiceException("请填写店长手机号");
//        }
//        DepartmentPostDto managerDepartmentPostInfo = managerDepartmentPostList.get(0);
//        user = BeanUtils.copyProperties(pageRegisterDto, TUser.class);
//        String password = StringUtil.toMD5(pageRegisterDto.getUserName()+pageRegisterDto.getPwd());
//        user.setPassword(password);
//        user.setRealname(pageRegisterDto.getRealName());
//        user.setUsername(pageRegisterDto.getUserName());
//        user.setSystem(SystemType.B_APP_SYSTEM.getValue());
//        user.setLogicDelete(LogicDelete.NOT_DELETE.getValue());
//        user.setStatus(UserStatus.PENDING.getValue());
//        user.setCreateTime(new Date());
//        user.setCompanyId(managerDepartmentPostInfo.getCompanyId());
//        user.setAddType(AddType.ADD.getValue());
//        userDao.insert(user);
//        //添加用户部门关联表
//        TUserDepartmentPost userDepartmentPost = new TUserDepartmentPost();
//        userDepartmentPost.setUserId(user.getId());
//        userDepartmentPost.setDepartmentId(pageRegisterDto.getDepartmentId());
//        userDepartmentPost.setPostId(pageRegisterDto.getPostId());
//        userDepartmentPost.setIsUsed(IsUsed.NOT_USED.getValue());
//        userDepartmentPostDao.insert(userDepartmentPost);
//    }
//
//    /**
//     * 该门店下待审核的员工
//     * @param departmentId
//     * @param systemType
//     * @return
//     * @throws Exception
//     */
//    public List<TobUserDto> pendingUserList(Long departmentId, SystemType systemType) throws Exception {
//        QLBuilder ql = new QLBuilder();
//        ql.setMainClause("SELECT new com.drip.common.dto.org.TobUserDto(tudp,tdep,tp,tu) FROM TUserDepartmentPost tudp, TDepartment tdep, TPost tp,TUser tu WHERE tudp.departmentId = tdep.id and tudp.postId=tp.id and tudp.userId = tu.id and tdep.companyId=tu.companyId");
//        ql.and(Filter.eq("tu.logicDelete", LogicDelete.NOT_DELETE.getValue()));
//        ql.and(Filter.eq("tdep.logicDelete", LogicDelete.NOT_DELETE.getValue()));
////        ql.and(Filter.eq("tu.companyId", UserUtil.tobCurrentUser().getCompanyId()));
////        ql.and(Filter.eq("tu.companyId", 169));
////        ql.and(Filter.eq("tdep.id",departmentId));
////        ql.and(Filter.eq("tu.status", UserStatus.PENDING.getValue()));
////        ql.and(Filter.eq("tudp.isUsed",IsUsed.NOT_USED.getValue()));
//        ql.add(" order by tu.createTime desc");
//        return userDepartmentPostDao.findManyByJpql(ql);
//    }

}
